/**  
 * @Title: AdSlideController.java
 * @Package com.limit.control.admin
 * @author maoyun(maoyun0903@163.com)
 * @date 2014-4-1 下午11:09:45
 * @version V1.0
 */ 
package com.limit.control.admin;

import java.io.File;
import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.upload.UploadFile;
import com.limit.control.admin.validate.SlideValidator;
import com.limit.exception.HHFileSystemException;
import com.limit.model.AdSlide;
import com.limit.utils.HHFile;
import com.limit.utils.PropertiesUtil;

/** 
 * <br/>
 * @author maoyun(maoyun0903@163.com)
 * @date 2014-4-1 下午11:09:45 
 * @version V1.0
 */

public class AdSlideController extends BaseController {
	
	
	/**
	 * 滚图列表管理
	 */
	public void index(){
		int p = this.getParaToInt("p",1);
		this.setAttr("slides", AdSlide.dao.pageAllList(p , pageSize));
		render("slides.html");
	}
	
	/**
	 * 视图
	 */
	public void view(){
		this._commonSetId();
		AdSlide adSlide = new AdSlide();
		if(id > 0){
			adSlide = AdSlide.dao.findById(id);
		}
		this.setAttr("adSlide", adSlide);
		render("slide_view.html");
	}
	
	
	/**
	 * 添加
	 */
	@Before(SlideValidator.class)
	public void save(){
		UploadFile uploadFile = this.getFile();
		//重命名文件
		AdSlide slide = this.getModel(AdSlide.class);
		slide.set("create_time", new Date());
		if(null != uploadFile){
			String newFileName = System.currentTimeMillis()+HHFile.getExtension(uploadFile.getOriginalFileName());
			String path = this._uploadFile(uploadFile, newFileName,PropertiesUtil.load("slide_path"));
			slide.set("image_path", path + newFileName);
		}
		slide.save();
		this.index();
		
	}

	/**
	 * 更新
	 */
	@Before(SlideValidator.class)
	public void update(){
		//对比new_image和old_image字段，删除以前的文件，上传新的
		UploadFile uploadFile = this.getFile();
		String old_path = this.getPara("old_image_path", "");
		AdSlide slide = this.getModel(AdSlide.class);
		if(null!=uploadFile && !uploadFile.getFile().getPath().equals(old_path)){
			String newFileName = System.currentTimeMillis()+HHFile.getExtension(uploadFile.getOriginalFileName());
			try {
				HHFile.deleteFile(old_path);
			} catch (HHFileSystemException e) {
				System.out.println(e.getMessage());
			}
			String path = this._uploadFile(uploadFile, newFileName,PropertiesUtil.load("slide_path"));
			
			slide.set("image_path", path+newFileName);
		}else{
			slide.set("image_path", old_path);
		}
		slide.update();
		this.index();
	}
	
	
	/**
	 * 禁用
	 */
	public void disable(){
		this._commonSetId();
		AdSlide.dao.findById(id).set("disable", 1).update();
		this.index();
	}
	
	/**
	 * 解禁
	 */
	public void renew(){
		this._commonSetId();
		AdSlide.dao.findById(id).set("disable", -1).update();
		this.index();
		
	}
	
	public void delete(){
		this._commonSetId();
		AdSlide.dao.deleteById(id);
		this.index();
	}
	
	
}
